<template>
  <div>
    <el-form :inline="true" :model="searchForm" class="filter-form">
      <el-form-item label="医生">
        <el-select v-model="searchForm.doctorId" placeholder="请选择" clearable>
          <el-option v-for="item in doctorList" :key="item.doctorId" :label="item.doctorName" :value="item.doctorId" />
        </el-select>
      </el-form-item>
      <el-form-item label="科室">
        <el-select v-model="searchForm.deptId" placeholder="请选择" clearable>
          <el-option v-for="item in deptList" :key="item.deptId" :label="item.deptName" :value="item.deptId" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="searchForm.status" placeholder="请选择" clearable>
          <el-option label="启用" :value="1" />
          <el-option label="禁用" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="searchForm.dateRange"
          type="daterange"
          range-separator="—"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchList">查询</el-button>
        <el-button @click="handleAdd">新增</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="tableData" border style="width: 100%; margin-top: 20px;">
      <el-table-column type="index" label="序号" width="60" />
      <el-table-column prop="doctorName" label="医生名称" />
      <el-table-column prop="deptName" label="科室" />
      <el-table-column prop="fuwu" label="服务" />
      <el-table-column prop="weekday" label="出诊星期" />
      <el-table-column prop="timeSlot" label="时间段" />
      <el-table-column prop="maxAppointments" label="诊疗总数" />
      <el-table-column prop="status" label="状态">
        <template slot-scope="scope">
          <span :style="{ color: scope.row.status == 1 ? '#67C23A' : '#F56C6C' }">
            {{ scope.row.status == 1 ? '正常' : '禁用' }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="创建时间" />
      <el-table-column label="操作" width="120">
        <template slot-scope="scope">
          <el-button type="text" size="mini" @click="handleEdit(scope.row)">修改</el-button>
          <el-button type="text" size="mini" @click="handleDisable(scope.row)">禁用</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      style="margin-top: 20px; text-align: right;"
      background
      layout="prev, pager, next, sizes, jumper"
      :total="total"
      :page-size="searchForm.pageSize"
      :current-page="searchForm.pageNum"
      @current-change="handlePageChange"
      @size-change="handleSizeChange"
    />

    <el-dialog title="出诊规律管理-规律详情" :visible.sync="dialogVisible" width="60%">
      <el-form :model="ruleForm" label-width="100px">
        <el-form-item label="医生">
          <el-select v-model="ruleForm.doctorId" placeholder="请选择" filterable>
            <el-option v-for="item in doctorList" :key="item.doctorId" :label="item.doctorName" :value="item.doctorId" />
          </el-select>
        </el-form-item>
        <el-form-item label="出诊科室">
          <el-select v-model="ruleForm.deptId" placeholder="请选择" filterable>
            <el-option v-for="item in deptList" :key="item.deptId" :label="item.deptName" :value="item.deptId" />
          </el-select>
        </el-form-item>
        <el-form-item label="服务">
          <el-select v-model="ruleForm.fuwu" placeholder="请选择" filterable>
            <el-option v-for="item in serviceList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="规律设置">
          <el-radio-group v-model="ruleForm.ruleType">
            <el-radio :label="'unified'">统一设置</el-radio>
            <el-radio :label="'separate'">分开设置</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 统一设置 -->
        <div v-if="ruleForm.ruleType === 'unified'" style="margin-bottom: 10px;">
          <el-checkbox-group v-model="unifiedWeekdays">
            <el-checkbox v-for="item in weekOptions" :key="item.value" :label="item.value">{{ item.label }}</el-checkbox>
          </el-checkbox-group>
        </div>

        <el-table v-if="ruleForm.ruleType === 'unified'" :data="ruleForm.timeRules" border>
          <el-table-column prop="period" label="午别" width="80">
            <template slot-scope="scope">
              <el-checkbox v-model="scope.row.checked">{{ scope.row.label }}</el-checkbox>
            </template>
          </el-table-column>
          <el-table-column prop="startTime" label="开始时间">
            <template slot-scope="scope">
              <el-time-picker v-model="scope.row.startTime" placeholder="请选择" :disabled="!scope.row.checked" />
            </template>
          </el-table-column>
          <el-table-column prop="endTime" label="结束时间">
            <template slot-scope="scope">
              <el-time-picker v-model="scope.row.endTime" placeholder="请选择" :disabled="!scope.row.checked" />
            </template>
          </el-table-column>
          <el-table-column prop="limitType" label="号源限制">
            <template slot-scope="scope">
              <el-select v-model="scope.row.limitType" placeholder="请选择" :disabled="!scope.row.checked">
                <el-option label="限制" value="limit" />
                <el-option label="不限" value="unlimit" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="total" label="号源总数">
            <template slot-scope="scope">
              <el-input v-model="scope.row.total" :disabled="!scope.row.checked" style="width: 60px;" />
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态">
            <template slot-scope="scope">
              <span :style="{ color: scope.row.checked ? '#67C23A' : '#F56C6C' }">
                {{ scope.row.checked ? '启用' : '禁用' }}
              </span>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分开设置 -->
        <el-collapse v-if="ruleForm.ruleType === 'separate'">
          <el-collapse-item v-for="week in ruleForm.weekRules" :key="week.weekday" :title="weekOptions[week.weekday-1].label">
            <el-checkbox v-model="week.checked">启用本星期</el-checkbox>
            <el-table :data="week.timeRules" border>
              <el-table-column prop="period" label="午别" width="80">
                <template slot-scope="scope">
                  <el-checkbox v-model="scope.row.checked">{{ scope.row.label }}</el-checkbox>
                </template>
              </el-table-column>
              <el-table-column prop="startTime" label="开始时间">
                <template slot-scope="scope">
                  <el-time-picker v-model="scope.row.startTime" placeholder="请选择" :disabled="!scope.row.checked" />
                </template>
              </el-table-column>
              <el-table-column prop="endTime" label="结束时间">
                <template slot-scope="scope">
                  <el-time-picker v-model="scope.row.endTime" placeholder="请选择" :disabled="!scope.row.checked" />
                </template>
              </el-table-column>
              <el-table-column prop="limitType" label="号源限制">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.limitType" placeholder="请选择" :disabled="!scope.row.checked">
                    <el-option label="限制" value="limit" />
                    <el-option label="不限" value="unlimit" />
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column prop="total" label="号源总数">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.total" :disabled="!scope.row.checked" style="width: 60px;" />
                </template>
              </el-table-column>
              <el-table-column prop="status" label="状态">
                <template slot-scope="scope">
                  <span :style="{ color: scope.row.checked ? '#67C23A' : '#F56C6C' }">
                    {{ scope.row.checked ? '启用' : '禁用' }}
                  </span>
                </template>
              </el-table-column>
            </el-table>
          </el-collapse-item>
        </el-collapse>

        <div style="margin: 10px 0; color: #f56c6c;">
          1、统一设置：支持每个星期批量设置规律；每个星期规律午别、时间段、号源一致<br />
          2、分开设置：支持每个星期批量设置规律，每个星期规律午别、时间段、号源可以单独设置<br />
          3、同一个医生同一服务、同一星期一个午别只能设置一个
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitRule">提交</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="danger" @click="handleDelete">删除</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';
export default {
  data() {
    return {
      searchForm: {
        pageNum: 1,
        pageSize: 10,
        doctorId: '',
        deptId: '',
        status: '',
        dateRange: []
      },
      doctorList: [],
      deptList: [],
      tableData: [],
      total: 0,
      defaultAvatar: 'https://img1.baidu.com/it/u=1894217312,3606262392&fm=253&fmt=auto&app=138&f=JPEG?w=200&h=200',
      dialogVisible: false,
      ruleForm: {
        doctorId: '',
        deptId: '',
        fuwu: '',
        ruleType: 'unified',
        weekdays: [],
        timeRules: [
          { label: '上午', period: '上午', checked: false, startTime: '', endTime: '', limitType: 'limit', total: 30, status: 1 },
          { label: '下午', period: '下午', checked: false, startTime: '', endTime: '', limitType: 'limit', total: 30, status: 1 },
          { label: '晚上', period: '晚上', checked: false, startTime: '', endTime: '', limitType: 'limit', total: 30, status: 1 },
          { label: '全天', period: '全天', checked: false, startTime: '', endTime: '', limitType: 'limit', total: 30, status: 1 }
        ]
      },
      unifiedWeekdays: [1],
      weekOptions: [
        { value: 1, label: '星期一' },
        { value: 2, label: '星期二' },
        { value: 3, label: '星期三' },
        { value: 4, label: '星期四' },
        { value: 5, label: '星期五' },
        { value: 6, label: '星期六' },
        { value: 7, label: '星期日' }
      ],
      serviceList: [
        { id: 1, name: '图文问诊' },
        { id: 2, name: '视频问诊' }
      ]
    };
  },
  created() {
    this.fetchDoctorList();
    this.fetchDeptList();
    this.fetchList();
  },
  methods: {
    fetchDoctorList() {
      axios.get('/doctors/list').then(res => {
        this.doctorList = res.data || [];
      });
    },
    fetchDeptList() {
      axios.get('/departments/list', { params: { pageNum: 1, pageSize: 100 } }).then(res => {
        this.deptList = res.data.records || [];
        console.log('deptList:', this.deptList);
      });
    },
    fetchList() {
      axios.get('/schedules/list2', {
        params: {
          pageNum: this.searchForm.pageNum,
          pageSize: this.searchForm.pageSize,
          doctorId: this.searchForm.doctorId,
          deptId: this.searchForm.deptId,
          status: this.searchForm.status,
          startTime: this.searchForm.dateRange[0] || '',
          endTime: this.searchForm.dateRange[1] || ''
        }
      }).then(res => {
        if (Array.isArray(res.data)) {
          this.tableData = res.data;
          this.total = res.data.length;
        } else if (res.data && Array.isArray(res.data.records)) {
          this.tableData = res.data.records;
          this.total = res.data.total || res.data.records.length;
        } else {
          this.tableData = [];
          this.total = 0;
        }
      });
    },
    handlePageChange(page) {
      this.searchForm.pageNum = page;
      this.fetchList();
    },
    handleSizeChange(size) {
      this.searchForm.pageSize = size;
      this.fetchList();
    },
    handleAdd() {
      this.ruleForm = {
        doctorId: '',
        deptId: '',
        fuwu: '',
        ruleType: 'unified',
        weekdays: [],
        timeRules: [
          { label: '上午', period: '上午', checked: false, startTime: '', endTime: '', limitType: 'limit', total: 30, status: 1 },
          { label: '下午', period: '下午', checked: false, startTime: '', endTime: '', limitType: 'limit', total: 30, status: 1 },
          { label: '晚上', period: '晚上', checked: false, startTime: '', endTime: '', limitType: 'limit', total: 30, status: 1 },
          { label: '全天', period: '全天', checked: false, startTime: '', endTime: '', limitType: 'limit', total: 30, status: 1 }
        ]
      };
      this.dialogVisible = true;
    },
    handleEdit(row) {
      this.$message.info('点击了修改: ' + row.doctorName);
    },
    handleDisable(row) {
      this.$message.info('点击了禁用: ' + row.doctorName);
    },
    submitRule() {
      const rulesList = [];
      if (this.ruleForm.ruleType === 'unified') {
        this.unifiedWeekdays.forEach(weekday => {
          this.ruleForm.timeRules.forEach(row => {
            if (row.checked) {
              rulesList.push({
                doctorId: this.ruleForm.doctorId,
                deptId: this.ruleForm.deptId,
                fuwu: this.ruleForm.fuwu,
                weekday: weekday,
                period: row.label,
                startTime: row.startTime,
                endTime: row.endTime,
                limitType: row.limitType,
                total: row.total,
                status: 1
              });
            }
          });
        });
      } else {
        // 分开设置逻辑
      }
      axios.post('/api/scheduleRules/add', rulesList).then(res => {
        if (res.data === 'success') {
          this.$message.success('新增成功');
          this.dialogVisible = false;
          this.fetchList();
        } else {
          this.$message.error('新增失败');
        }
      });
    },
    handleDelete() {
      // 这里写删除逻辑
      this.$message.warning('点击了删除');
    }
  }
};
</script>

<style scoped>
.filter-form {
  margin-bottom: 20px;
}
</style>